package cadc.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.windpicker.common.utils.Encoder;

import cadc.daos.FileItemDao;
import cadc.models.FileItem;

@SuppressWarnings("serial")
public class Upload extends UserAction {
	private FileItem fi = new FileItem();
	private FileItemDao fileItemDao;
	private String storageDir;
	private int fileId;
	
	public String execute(){
		this.setFileId(saveFile(fi));
		return SUCCESS;
	}
	
	private int saveFile(FileItem fi){
		if(fi.getSize()>0&&fi.getItemFileName()!=null&&fi.getItemFileName().length()!=0){
			fi.setKey(Encoder.encryptMD5(fi.getKey()));
			int fileId = fileItemDao.saveFileItem(fi);
			try {
				InputStream in = new FileInputStream(fi.getItem());
				OutputStream out = new FileOutputStream(new File(storageDir+fileId));
				byte[] buffer = new byte[10240];
				int len;
				len = in.read(buffer);
				while(len>0){
					out.write(buffer,0,len);
					len = in.read(buffer);
				}
				in.close();
				out.flush();
				out.close();
				return fileId;
			} catch (FileNotFoundException e) {
				return 0;
			}catch (IOException e) {
				return 0;
			}
			
		}else return 0;
	}
	
	public void setFiledata(File filedata) {
		fi.setItem(filedata);
	}
	public void setFiledataFileName(String filedataFileName) {
		fi.setItemFileName(filedataFileName);
	}
	public void setFiledataContentType(String filedataContentType) {
		fi.setItemContentType(filedataContentType);
	}
	public void setSize(int size) {
		fi.setSize(size);
	}
	public void setKey(String key) {
		fi.setKey(key);
	}
	public void setFileItemDao(FileItemDao fileItemDao) {
		this.fileItemDao = fileItemDao;
	}
	public FileItemDao getFileItemDao() {
		return fileItemDao;
	}
	public void setStorageDir(String storageDir) {
		this.storageDir = storageDir;
	}
	public String getStorageDir() {
		return storageDir;
	}

	public void setFileId(int fileId) {
		this.fileId = fileId;
	}

	public int getFileId() {
		return fileId;
	}
}
